package com.qiaodata.datatrans.web;

import com.alibaba.fastjson.JSONObject;
import com.qiaodata.datatrans.entity.ResumerAndStatus;
import com.qiaodata.datatrans.repository.ResumerRepository;
import com.qiaodata.datatrans.transfor.OutDataToFormat;
import com.qiaodata.datatrans.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/5 0005.
 */
@RestController
@Slf4j
public class QZTxtToMongoController {

    @Autowired
    private OutDataToFormat outDataToFormat;
    @Autowired
    private ResumerRepository resumerRepository;

//    @RequestMapping(value = "/importdata", method = {RequestMethod.POST, RequestMethod.GET})
//    public void importData(@RequestParam("paths") String paths) throws Exception {
//        if (paths==null || "".equals(paths.trim())) {
//            log.debug("传递参数为空！");
//            return ;
//        }
//        String[] split = paths.split(",");
//        if (split.length<1) {
//            log.debug("传递参数为空！");
//            return ;
//        }
//        for (int i=0; i<split.length; i++) {
//            String path = split[i].trim();
//            //String pathId = path.trim();
//            //从磁盘读数据,/share/20161202/,白天开始从root下读取/root/
//            //String pathStr = "/root/"+pathId;
////            String pathStr = "D:/share/20161202/"+pathId;
//
//            //初步解析json
//            traverseFolderAndDealData(path);
//        }
//
//        System.out.println("=========end===========");
//
//    }

    @RequestMapping(value = "/importdata", method = {RequestMethod.POST, RequestMethod.GET})
    public Object importData(@RequestBody JSONObject jsonObject, @RequestParam("filepath") String filepath) throws Exception {
        if (jsonObject==null || "".equals(jsonObject.toString()) || filepath==null || "".equals(filepath)) {
            log.debug("传递参数为空！");
            return JsonResult.getInstance("0");
        }

        String b = convertFileToMongo(jsonObject, filepath);
        if ("1".equals(b)) {
            System.out.println("=========end===========");
            return JsonResult.getInstance(b);
        } else {
            System.out.println("=========end===========");
            return JsonResult.getInstance(b);
        }

    }

//    @RequestMapping(value = "/importdata2", method = {RequestMethod.POST, RequestMethod.GET})
//    public Object importData2(@RequestParam("str") String str) throws Exception {
//        if (str==null || "".equals(str)) {
//            log.debug("传递参数为空！");
//            return JsonResult.getInstance("0");
//        }
//        System.out.print(str);
////        boolean b = convertFileToMongo(jsonObject);
////        if (b) {
////            System.out.println("=========end===========");
////            return JsonResult.getInstance("1");
////        } else {
////            System.out.println("=========end===========");
////            return JsonResult.getInstance("0");
////        }
//        return null;
//    }


//    public void traverseFolderAndDealData(String path) throws ParseException, IOException {
//        int fileNum = 0, folderNum = 0;
//        File file = new File(path);
//        //String err_filePath = "/root/app/error/";
////        String err_filePath = "D:/share/error/";
//        //String strTxt = err_filePath + fi_path+"_error.txt";
//        String strTxt = path + "//error.txt";
//        //记录错误的信息
////        FileWriter fw1 = new FileWriter(strTxt);
//        FileWriter fw1 = new FileWriter(strTxt);//本地模式存储
//        if (file.exists()) {
//            LinkedList<File> list = new LinkedList<File>();
//            File[] files = file.listFiles();// 该文件目录下文件全部放入数组
//            for (File file2 : files) {
//                String fileName = file2.getName();
//                if (file2.isDirectory()) {
//                    System.out.println("文件夹:" + file2.getAbsolutePath());
//                    list.add(file2);
//                    fileNum++;
//                } else if (fileName.endsWith("txt")){
//                    System.out.println("文件:" + file2.getAbsolutePath());
//                    //拿到文件
////                    String filePath ="/root/middleid_1.txt";
//                    String filePath =file2.getAbsolutePath();
//                    List<String> resumes = ReadTxtUtil.readTxtFile(filePath);//按行读取txt文档
//                    //处理文件数据
//                    if (resumes==null || resumes.size()<1) {
//                        return ;
//                    }
//                    for (String resumStr : resumes) {
//                        JSONObject jsonObject = JSONObject.parseObject(resumStr);
//                        if (jsonObject==null || "".equals(jsonObject.toString())) {
//                            continue;
//                        }
//                        //初步解析json
//                        Map<String, String> qzJson = this.getQZJson(jsonObject);
//                        String p1 = qzJson.get("P_PersonalInformation");
//                        String p2 = qzJson.get("P_Resume");
//                        if (p1==null || "".equals(p1) || p2==null || "".equals(p2)) {
//                            log.debug("传递参数为空！");
//                            continue;
//                        }
//                        try {
//                            JSONObject parse1 = (JSONObject) JSONObject.parse(p1);
//                            JSONObject parse2 = (JSONObject) JSONObject.parse(p2);
//                            long l1 = System.currentTimeMillis();
//                            //简历转换
//                            QuanZhiResumer resumer = outDataToFormat.getQuanZhiResumer(parse1, parse2);
//                            long l2 = System.currentTimeMillis();
//                            System.out.print("转换一条用时：" + (l2 - l1) + "ms");
//                            //插入到mongo数据库
//                            resumerRepository.save(resumer);
//                            log.debug("数据入库成功！");
//
//                            long l3 = System.currentTimeMillis();
//
//                            System.out.print("入库一条用时：" + (l3 - l2) + "ms");
//                        } catch (Exception e) {
//                            log.error("数据入库失败！");
//                            //记录没有插入成功的文件路径
//                            fw1.write(resumStr+"\r\n");
//                            fw1.flush();
//
//                            continue;
//                        }
//                    }
//
//                    folderNum++;
//                } else {
//                    continue;
//                }
//            }
//            fw1.close();//关闭资源
////            File temp_file;
////            while (!list.isEmpty()) {
////                temp_file = list.removeFirst();
////                files = temp_file.listFiles();
////                for (File file2 : files) {
////                    if (file2.isDirectory()) {
////                        System.out.println("文件夹:" + file2.getAbsolutePath());
////                        list.add(file2);
////                        fileNum++;
////                    } else {
////                        System.out.println("文件:" + file2.getAbsolutePath());
////                        folderNum++;
////                    }
////                }
////            }
//        } else {
//            System.out.println("文件不存在!");
//        }
//        System.out.println("文件共有:" + folderNum + ",文件夹共有:" + fileNum);
//
//    }

    private Map<String, String> getQZJson(JSONObject jsonObject) {
        Map<String, String> map = new HashMap<String, String>();
        if (jsonObject==null || "".equals(jsonObject.toString())) {
            map.put("P_PersonalInformation", "");
            map.put("P_Resume", "");
            return map;
        }
        String[] split = jsonObject.toString().split("P_PersonalInformation\":");
        if (split.length<2) {
            map.put("P_PersonalInformation", "");
            map.put("P_Resume", "");
            return map;
        }
        String[] split1 = split[1].split("P_Resume\":");
        if (split1.length<2) {
            map.put("P_PersonalInformation", "");
            map.put("P_Resume", "");
            return map;
        }
        String p1 = split1[0].substring(0, split1[0].length() - 2);
        String p2 = split1[1].substring(0, split1[1].length() - 1);
        map.put("P_PersonalInformation", p1);
        map.put("P_Resume", p2);
        return map;
    }

//    public boolean convertFileToMongo(String filePath) throws ParseException, IOException {
//        boolean ret = false;
//
//        List<String> resumes = ReadTxtUtil.readTxtFile(filePath);//按行读取txt文档
//
//        //处理文件数据
//        if (resumes == null || resumes.size() < 1) {
//            ret = false;
//            return ret;
//        }
//
//        for (String resumStr : resumes) {
//            JSONObject jsonObject = JSONObject.parseObject(resumStr);
//            if (jsonObject == null || "".equals(jsonObject.toString())) {
//                continue;
//            }
//            //初步解析json
//            Map<String, String> qzJson = this.getQZJson(jsonObject);
//            String p1 = qzJson.get("P_PersonalInformation");
//            String p2 = qzJson.get("P_Resume");
//            if (p1 == null || "".equals(p1) || p2 == null || "".equals(p2)) {
//                log.debug("传递参数为空！");
//                continue;
//            }
//            try {
//                JSONObject parse1 = (JSONObject) JSONObject.parse(p1);
//                JSONObject parse2 = (JSONObject) JSONObject.parse(p2);
//                long l1 = System.currentTimeMillis();
//                //简历转换
//                QuanZhiResumer resumer = outDataToFormat.getQuanZhiResumer(parse1, parse2);
//                long l2 = System.currentTimeMillis();
//                System.out.print("转换一条用时：" + (l2 - l1) + "ms");
//                //插入到mongo数据库
//                resumerRepository.save(resumer);
//                log.debug("数据入库成功！");
//
//                long l3 = System.currentTimeMillis();
//
//                System.out.print("入库一条用时：" + (l3 - l2) + "ms");
//
//                ret = true;
//            } catch (Exception e) {
//                log.error("数据入库失败！");
//                ret = false;
//                //记录没有插入成功的文件路径
//                //fw1.write(resumStr+"\r\n");
//                //fw1.flush();
//            }
//        }
//
//        return ret;
//    }

    public String convertFileToMongo(JSONObject jsonObject, String filepath) throws ParseException, IOException {

//        List<String> resumes = ReadTxtUtil.readTxtFile(filePath);//按行读取txt文档

        //处理文件数据
        if (jsonObject == null || "".equals(jsonObject.toString())) {
            return "0";
        }

        //初步解析json
        Map<String, String> qzJson = this.getQZJson(jsonObject);
        String p1 = qzJson.get("P_PersonalInformation");
        String p2 = qzJson.get("P_Resume");
        if (p1 == null || "".equals(p1) || p2 == null || "".equals(p2)) {
            log.debug("传递参数为空！");
            return "0";
        }
        try {
            JSONObject parse1 = (JSONObject) JSONObject.parse(p1);
            JSONObject parse2 = (JSONObject) JSONObject.parse(p2);
            outDataToFormat.readTxtToMap(filepath);
            long l1 = System.currentTimeMillis();
            //简历转换
            System.out.println("quanzhiResumer start");
            ResumerAndStatus resumerAndStatus = outDataToFormat.getResumer(parse1, parse2);
            String status = resumerAndStatus.getStatus();
//            QuanZhiResumer resumer = outDataToFormat.getQuanZhiResumer(parse1, parse2);
            if ("2".equals(status)) {
                //转换失败范围PositionInfo
                return "2";
            } else if ("3".equals(status)) {
                //转换失败范围jobIntension
                return "3";
            } else if ("4".equals(status)) {
                //转换失败范围deliverInfo
                return "4";
            } else if ("5".equals(status)) {
                //转换失败范围educations
                return "5";
            } else if ("6".equals(status)) {
                //转换失败范围languages
                return "6";
            } else if ("7".equals(status)) {
                //转换失败范围skills
                return "7";
            } else if ("8".equals(status)) {
                //转换失败范围projects
                return "8";
            } else if ("9".equals(status)) {
                //转换失败范围projectsCnts
                return "9";
            } else if ("10".equals(status)) {
                //转换失败范围trainings
                return "10";
            } else if ("11".equals(status)) {
                //转换失败范围workCnts
                return "11";
            } else if ("12".equals(status)) {
                //转换失败范围works
                return "12";
            }

            System.out.println("quanzhiResumer end"+resumerAndStatus);
            if (resumerAndStatus==null) {
                return "13";
            }
            long l2 = System.currentTimeMillis();
            System.out.print("转换一条用时：" + (l2 - l1) + "ms");
            //插入到mongo数据库
            resumerRepository.save(resumerAndStatus.getQuanZhiResumer());
            //获取objid
//            QuanZhiResumer save = resumerRepository.save(resumer);
//            System.out.println("插入的Resumer的objid为"+save.getId());
            log.debug("数据入库成功！");

            long l3 = System.currentTimeMillis();

            System.out.print("入库一条用时：" + (l3 - l2) + "ms");

            return "1";
        } catch (Exception e) {
            log.error("数据入库失败！");
            return "0";
            //记录没有插入成功的文件路径
            //fw1.write(resumStr+"\r\n");
            //fw1.flush();
        }

    }

}
